<?php


namespace App\Controller;

use App\Logic\Dictionary;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;

/**
 * Class ExtStopwordsController
 * @package App\Controller
 * @Controller(prefix="/ext/stopwords")
 *
 */
class ExtStopwordsController extends AbstractController
{

    /**
     * @var Dictionary
     */
    protected $dictionary;

    public function __construct(Dictionary $dictionary)
    {
        parent::__construct();
        $this->dictionary = $dictionary;
    }

    protected function init()
    {
        $this->dictionary->extStopWords();
    }

    /**
     * @GetMapping(path="")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function index()
    {
        $this->init();
        $content = $this->dictionary->dic();
        $etag = md5($content);
        return $this->response->raw($content)
            ->withHeader('ETag', $etag)
            ->withHeader('Last-Modified', $this->dictionary->lastModified());
    }

    /**
     * @GetMapping(path="json")
     */
    public function show()
    {
        $this->init();

        return $this->responseJson->data($this->dictionary->read())->success();
    }

    /**
     * @PostMapping(path="append")
     */
    public function append()
    {
        $this->init();

        $words = $this->request->input('words');
        if ($this->dictionary->append($words)) {
            return $this->responseJson->success();
        }
        return $this->responseJson->failed();
    }

    /**
     * @PostMapping(path="remove")
     */
    public function remove()
    {
        $this->init();

        $words = $this->request->input('words');
        if ($this->dictionary->remove($words)) {
            return $this->responseJson->success();
        }
        return $this->responseJson->failed();
    }

    /**
     * 清洗数据
     * @GetMapping(path="flush")
     */
    public function flush()
    {
        $this->init();

        if ($this->dictionary->flush()) {
            return $this->responseJson->success();
        }
        return $this->responseJson->failed();
    }
}